package com.ruoyi.system.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.ActivityConstant;
import com.ruoyi.common.core.constant.DataScopeConstants;
import com.ruoyi.common.core.constant.LeaveConstant;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.RegExUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.Activity;
import com.ruoyi.system.domain.SchoolRole;
import com.ruoyi.system.service.IActivityService;
import com.ruoyi.system.service.ISchoolRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.Leave;
import com.ruoyi.system.service.ILeaveService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 活动请假条增删改查Controller
 * 
 * @author hyb
 * @date 2023-02-26
 */
@RestController
@RequestMapping("/leave")
public class LeaveController extends BaseController
{
    @Autowired
    private ILeaveService leaveService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISchoolRoleService schoolRoleService;

    @Autowired
    private ISysUserService sysUserService;

    /*
    *
    * 审批工作
    * */
    @RequiresPermissions("leave:leave:approve")
    @PostMapping("/approve")
    public AjaxResult approve(@RequestBody Leave leave){

        Set<String> dataScope = SecurityUtils.getDataScope();
        for (String s : dataScope) {
            //如果是个人权限,只能更新个人的
            if(s.equals(DataScopeConstants.DATA_SCOPE_SELF)
                && !leave.getApproverUserId().equals(SecurityUtils.getUserId())
            ){
                return AjaxResult.error("此条数据非自己审批的数据");
            }
            if(s.equals(DataScopeConstants.DATA_SCOPE_DEPT)
                && !leave.getPf1().equals(String.valueOf(SecurityUtils.getDeptId()))
            ){
                return AjaxResult.error("此数据非本部门数据");
            }
            //如果是全部,都能更新
        }
        Long userId = SecurityUtils.getUserId();
        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setUserId(userId);
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if(schoolRoles.size()==0){
            return AjaxResult.error("该用户未认证学校信息");
        }
        schoolRole=schoolRoles.get(0);


        leave.setApproverUserId(userId);
        leave.setApproverEmail(schoolRole.getEmail());
        leave.setApproverName(schoolRole.getName());
        leave.setApproverNumber(schoolRole.getNumber());
        leave.setApproverSex(schoolRole.getSex());
        leave.setApproverPhone(schoolRole.getPhone());
        leave.setUpdateTime(DateUtils.getNowDate());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        leave.setPf3(format);
        leaveService.updateLeave(leave);
        return AjaxResult.success();

    }


    /**
     * 查询活动请假条增删改查列表
     */
    @RequiresPermissions("leave:leave:list")
    @GetMapping("/list")
    public TableDataInfo list(Leave leave)
    {

        Set<String> dataScope = SecurityUtils.getDataScope();
        for (String s : dataScope) {
            //如果是个人权限,只能查询自己要审批的假条
            if(DataScopeConstants.DATA_SCOPE_SELF.equals(s)){
                leave.setApproverUserId(SecurityUtils.getUserId());
            }
            //如果是部门数据权限,只能查自己部门的
            if(DataScopeConstants.DATA_SCOPE_DEPT.equals(s)){
                leave.setPf1(String.valueOf(SecurityUtils.getDeptId()));
            }
            //如果是全部用户权限,不用拼接字段,查所有
        }
        startPage();
        List<Leave> list = leaveService.selectLeaveList(leave);
        return getDataTable(list);
    }

    /**
     * 导出活动请假条增删改查列表
     */
    @RequiresPermissions("leave:leave:export")
    @Log(title = "活动请假条增删改查", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Leave leave)
    {
        Set<String> dataScope = SecurityUtils.getDataScope();
        for (String s : dataScope) {
            //如果是个人权限,只能查询自己要审批的假条
            if(DataScopeConstants.DATA_SCOPE_SELF.equals(s)){
                leave.setApproverUserId(SecurityUtils.getUserId());
            }
            //如果是部门数据权限,只能查自己部门的
            if(DataScopeConstants.DATA_SCOPE_DEPT.equals(s)){
                leave.setPf1(String.valueOf(SecurityUtils.getDeptId()));
            }
            //如果是全部用户权限,不用拼接字段,查所有
        }
        List<Leave> list = leaveService.selectLeaveList(leave);
        ExcelUtil<Leave> util = new ExcelUtil<Leave>(Leave.class);
        util.exportExcel(response, list, "活动请假条增删改查数据");
    }

    /**
     * 获取活动请假条增删改查详细信息
     */
    @RequiresPermissions("leave:leave:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(leaveService.selectLeaveById(id));
    }

    /**
     * 新增活动请假条增删改查
     */
    @RequiresPermissions("leave:leave:add")
    @Log(title = "活动请假条增删改查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Leave leave)
    {
        //活动是否存在
        Activity activity = new Activity();
        activity.setNumber(leave.getApproverNumber());
        List<Activity> list = activityService.selectActivityList(activity);
        if (list.size()==0){
            return AjaxResult.error("活动不存在");
        }

        //活动必须是开始后
        if(!activity.getStatus().equals(ActivityConstant.STARTING_STATUS)){
            return AjaxResult.error("活动未开始,不能请假");
        }

        if(!DateUtils.isMoreMaxDate(leave.getLaseTime(),leave.getStartTime())){
            return AjaxResult.error("结束时间应该比开始时间更晚");
        }

        if(!DateUtils.isMoreMaxDate(leave.getStartTime(),activity.getStartTime())){
            return AjaxResult.error("请假开始时间应该在活动开始时间之后");
        }

        if(!DateUtils.isMoreMaxDate(leave.getStartTime(),activity.getLastTime())){
            return AjaxResult.error("请假时间应该在活动开始期间进行");
        }

        if(!DateUtils.isMoreMaxDate(leave.getLaseTime(),activity.getLastTime())){
            return AjaxResult.error("请假结束时间不能超过活动结束时间");
        }

        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setNumber(leave.getUserNumber());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("学号不存在");
        }
        activity=list.get(0);
        schoolRole=schoolRoles.get(0);
        leave.setActivityId(activity.getId());
        leave.setActivityName(activity.getName());

        SysUser sysUser = sysUserService.selectUserById(schoolRole.getUserId());

        //检查是否已有请假条,最多一次请假机会
        Leave leave1 = new Leave();
        leave1.setActivityId(activity.getId());
        leave1.setUserId(sysUser.getUserId());
        List<Leave> leaves = leaveService.selectLeaveList(leave1);
        if (leaves.size()!=0){
            return AjaxResult.error("您只有一次请假的机会");
        }


        leave.setUserId(sysUser.getUserId());
        leave.setUserName(schoolRole.getName());
        leave.setUserEmail(schoolRole.getEmail());
        leave.setUserPhone(schoolRole.getPhone());
        leave.setUserSex(schoolRole.getSex());
        leave.setCreateTime(DateUtils.getNowDate());
        leave.setUpdateTime(DateUtils.getNowDate());
        leave.setStatus(LeaveConstant.CREATE_STATUS);
        leave.setPf1(String.valueOf(sysUser.getDeptId()));

        return toAjax(leaveService.insertLeave(leave));
    }


    @Log(title = "活动请假条增删改查", businessType = BusinessType.INSERT)
    @PostMapping("/inner/add")
    public AjaxResult innerAdd(@RequestBody Leave leave)
    {
        //活动是否存在

        Activity activity = activityService.selectActivityById(leave.getActivityId());
        if (activity==null){
            return AjaxResult.error("活动不存在");
        }

        //活动必须是开始后
        if(!activity.getStatus().equals(ActivityConstant.STARTING_STATUS)){
            return AjaxResult.error("活动未开始,不能请假");
        }



        if(!DateUtils.isMoreMaxDate(leave.getLaseTime(),leave.getStartTime())){
            return AjaxResult.error("结束时间应该比开始时间更晚");
        }

        if(!DateUtils.isMoreMaxDate(leave.getStartTime(),activity.getStartTime())){
            return AjaxResult.error("请假开始时间应该在活动开始时间之后");
        }


        if(DateUtils.isMoreMaxDate(leave.getStartTime(),activity.getLastTime())){
            return AjaxResult.error("请假时间应该在活动开始期间进行");
        }

        if(DateUtils.isMoreMaxDate(leave.getLaseTime(),activity.getLastTime())){
            return AjaxResult.error("请假结束时间不能超过活动结束时间");
        }


        SchoolRole schoolRole = new SchoolRole();
        schoolRole.setNumber(leave.getUserNumber());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(schoolRole);
        if (schoolRoles.size()==0){
            return AjaxResult.error("学号不存在");
        }




        schoolRole=schoolRoles.get(0);
        leave.setActivityId(activity.getId());
        leave.setActivityName(activity.getName());
        leave.setApproverNumber(activity.getNumber());

        SysUser sysUser = sysUserService.selectUserById(schoolRole.getUserId());
        //检查是否已有请假条,最多一次请假机会
        Leave leave1 = new Leave();
        leave1.setActivityId(activity.getId());
        leave1.setUserId(sysUser.getUserId());
        List<Leave> leaves = leaveService.selectLeaveList(leave1);
        if (leaves.size()!=0){
            return AjaxResult.error("您只有一次请假的机会");
        }

        leave.setUserId(sysUser.getUserId());
        leave.setUserName(schoolRole.getName());
        leave.setUserEmail(schoolRole.getEmail());
        leave.setUserNumber(schoolRole.getNumber());
        leave.setUserPhone(schoolRole.getPhone());
        leave.setUserSex(schoolRole.getSex());
        leave.setCreateTime(DateUtils.getNowDate());
        leave.setUpdateTime(DateUtils.getNowDate());
        leave.setStatus(LeaveConstant.CREATE_STATUS);
        leave.setPf1(String.valueOf(sysUser.getDeptId()));
        leave.setApproverNumber(activity.getNumber());



        return toAjax(leaveService.insertLeave(leave));
    }

    /**
     * 修改活动请假条增删改查
     */
    @RequiresPermissions("leave:leave:edit")
    @Log(title = "活动请假条增删改查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Leave leave)
    {
        return toAjax(leaveService.updateLeave(leave));
    }

    /**
     * 删除活动请假条增删改查
     */
    @RequiresPermissions("leave:leave:remove")
    @Log(title = "活动请假条增删改查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(leaveService.deleteLeaveByIds(ids));
    }
}
